package com.husd.framework.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class XmlUtil {
    public static final XmlMapper xmlMapper;

    static {
        xmlMapper = new XmlMapper();
        //xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
        xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static String toXml(Object object) throws JsonProcessingException {
        String s = xmlMapper.writeValueAsString(object);
        return "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + s;
    }


    public static <T> T toObject(String xml, TypeReference<T> valueTypeRef) throws JsonProcessingException {
        return xmlMapper.readValue(xml, valueTypeRef);
    }


}
